//输入一个链表的头节点，从尾到头反过来返回每个节点的值（用数组返回）。 
//
// 
//
// 示例 1： 
//
// 输入：head = [1,3,2]
//输出：[2,3,1] 
//
// 
//
// 限制： 
//
// 0 <= 链表长度 <= 10000 
//
// Related Topics 栈 递归 链表 双指针 👍 391 👎 0


package leetcode.editor.cn;

// [剑指 Offer 06]从尾到头打印链表

import java.util.Arrays;
import java.util.Stack;

public class CongWeiDaoTouDaYinLianBiaoLcof_JianZhiOffer06 {
    public static void main(String[] args) {
        Solution solution = new CongWeiDaoTouDaYinLianBiaoLcof_JianZhiOffer06().new Solution();
        ListNode head = getHead(new int[]{1, 3, 2});
        int[] arr = solution.reversePrint(head);
        System.out.println(Arrays.toString(arr));
    }

    public static ListNode getHead(int[] arr) {
        ListNode head = new CongWeiDaoTouDaYinLianBiaoLcof_JianZhiOffer06().new ListNode(arr[0]);
        ListNode p = head;

        for (int i = 1; i < arr.length; i++) {
            p.next = new CongWeiDaoTouDaYinLianBiaoLcof_JianZhiOffer06().new ListNode(arr[i]);
            p = p.next;
        }
        return head;
    }

    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     * int val;
     * ListNode next;
     * ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public int[] reversePrint(ListNode head) {
            if (head == null) return new int[]{};
            Stack stack = new Stack();
            ListNode cur = head;
            int i = 0;
            while (cur != null) {
                stack.push(cur.val);
                cur = cur.next;
                i++;
            }
            int[] ans = new int[i];
            i = 0;
            while (!stack.isEmpty()) {
                 ans[i++] = (int) stack.pop();
//                stack.pop();
            }
            return ans;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

    private class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    class Solution2 {
        public int[] reversePrint(ListNode head) {
            int i = 0;
            int[] arr = new int[10000];
            while (head != null) {
                arr[i++] = head.val;
                head = head.next;
            }
            int[] ans = new int[i];
            for (i = 0; i < ans.length; i++) {
                ans[i] = arr[ans.length - i - 1];
            }
            return ans;
        }
    }
}